<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 角色
 * App\Models\Role
 */
class Role extends Model
{
    use SoftDeletes;

    protected $guarded = ['id'];

    public $fields = [
        'title',      //权限名称 权限有可能对应一个菜单
        'status',     //启用状态 1表示启用
        'company_id', //权限所属单位的id 系统权限company_id为0
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联关系 N:N 角色和菜单权限多对多关联
     * 参数1:要去关联的类 参数2:中间表 参数3:中间表里本类id 参数4:中间表里关联类的id  参数5:本类主键id 参数6:关联类主键id
     * @return BelongsToMany
     */
    public function rules(): BelongsToMany
    {
        return $this->belongsToMany(Menu::class, 'role_id', 'rule_id')->orderBy('sort', 'desc');
    }

    /**
     * 关联关系 N:N  角色和用户多对多关联
     * @return BelongsToMany
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_roles', 'role_id', 'user_id');
    }


}
